/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.workless.modules.sys.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

//import com.workless.modules.database.datalink.jdbc.DBPool;
//import com.workless.modules.form.dto.Column;
//import com.workless.modules.form.service.FormService;
//import com.workless.modules.form.service.GenerateFormService;
//import com.workless.modules.form.utils.FormJsonUtils;
//import com.workless.modules.form.utils.FormOracleTableBuilder;
//import com.workless.modules.form.utils.FormTableBuilder;
import com.workless.modules.sys.utils.UserUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.workless.common.utils.DateUtils;
import com.workless.common.json.AjaxJson;
import com.workless.core.persistence.Page;
import com.workless.core.web.BaseController;
import com.workless.common.utils.StringUtils;
import com.workless.common.utils.excel.ExportExcel;
import com.workless.common.utils.excel.ImportExcel;
import com.workless.modules.sys.entity.JeeDataApp;
import com.workless.modules.sys.service.JeeDataAppService;

//import com.workless.modules.form.entity.Form;

/**
 * 数据应用Controller
 * @author kay
 * @version 2021-01-26
 */
@RestController
@RequestMapping(value = "/sys/jeeDataApp")
public class JeeDataAppController extends BaseController {

	@Autowired
	private JeeDataAppService jeeDataAppService;

	@ModelAttribute
	public JeeDataApp get(@RequestParam(required=false) String id) {
		JeeDataApp entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = jeeDataAppService.get(id);
		}
		if (entity == null){
			entity = new JeeDataApp();
		}
		return entity;
	}


	/**
	 * 数据应用列表数据
	 */
//	@RequiresPermissions("sys:jeeDataApp:list")
	@GetMapping("list")
	public AjaxJson list(JeeDataApp jeeDataApp, HttpServletRequest request, HttpServletResponse response) {
		jeeDataApp.setSid(UserUtils.getUser().getCompany().getId());
		Page<JeeDataApp> page = jeeDataAppService.findPage(new Page<JeeDataApp>(request, response), jeeDataApp);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 查询某表单
	 */
	@GetMapping("queryByName")
	public AjaxJson executeQueryByName(JeeDataApp jeeDataAppName) {
//		jeeDataAppName.setSid(UserUtils.getUser().getCompany().getId());
//		JeeDataApp jeeDataApp = jeeDataAppService.get(jeeDataAppName);executeSelectSql
		JeeDataApp jeeDataApp = jeeDataAppService.executeSelectOneSql("select * from jee_data_app where names='"+jeeDataAppName.getNames()+"' and sid='"+UserUtils.getUser().getCompany().getId()+"' ");
		return AjaxJson.success().put("jeeDataApp", jeeDataApp);
	}

	/**
	 * 根据Id获取数据应用数据
	 */
//	@RequiresPermissions(value={"sys:jeeDataApp:view","sys:jeeDataApp:add","sys:jeeDataApp:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(JeeDataApp jeeDataApp) {
		return AjaxJson.success().put("jeeDataApp", jeeDataApp);
	}


	/**
	 * 保存数据应用
	 */
//	@RequiresPermissions(value={"sys:jeeDataApp:add","sys:jeeDataApp:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(JeeDataApp jeeDataApp, Model model) throws Exception{
//		System.out.println(jeeDataApp.getIsNewRecord());
		jeeDataApp.setSid(UserUtils.getUser().getCompany().getId());
//		if(jeeDataAppService.get(jeeDataApp)!=null && jeeDataApp.getIsNewRecord()){
//			return AjaxJson.error("安装失败，该应用已安装！");
//		}
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(jeeDataApp);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
//		if(jeeDataApp.getIsNewRecord()) {
//			jeeDataApp.setSid(UserUtils.getUser().getCompany().getId());
//		}
		//新增或编辑表单保存
		jeeDataAppService.save(jeeDataApp);//保存
		return AjaxJson.success("保存数据应用成功!");
	}


	/**
	 * 批量删除数据应用
	 */
//	@RequiresPermissions("sys:jeeDataApp:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			jeeDataAppService.delete(new JeeDataApp(id));
		}
		return AjaxJson.success("删除数据应用成功!");
	}

	/**
	 * 导出excel文件
	 */
//	@RequiresPermissions("sys:jeeDataApp:export")
    @GetMapping("export")
    public AjaxJson exportFile(JeeDataApp jeeDataApp, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "数据应用"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<JeeDataApp> page = jeeDataAppService.findPage(new Page<JeeDataApp>(request, response, -1), jeeDataApp);
    		new ExportExcel("数据应用", JeeDataApp.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出数据应用记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
//	@RequiresPermissions("sys:jeeDataApp:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<JeeDataApp> list = ei.getDataList(JeeDataApp.class);
			for (JeeDataApp jeeDataApp : list){
				try{
					jeeDataAppService.save(jeeDataApp);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条数据应用记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条数据应用记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入数据应用失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入数据应用数据模板
	 */
//	@RequiresPermissions("sys:jeeDataApp:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "数据应用数据导入模板.xlsx";
    		List<JeeDataApp> list = Lists.newArrayList();
    		new ExportExcel("数据应用数据", JeeDataApp.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }


}